/*
 * TitleBar.cpp
 *
 *  Created on: 2011-1-12
 *      Author: Administrator
 */

#include "TitleBar.h"

CTitleBar* CTitleBar::NewL( const TRect& aRect, const CCoeControl* aParent )
	{
	CTitleBar* self = CTitleBar::NewLC(aRect, aParent);
	CleanupStack::Pop(self);
	return self;
	}

CTitleBar* CTitleBar::NewLC( const TRect& aRect,const CCoeControl* aParent )
	{
	CTitleBar* self = new(ELeave) CTitleBar();
	CleanupStack::PushL(self);
	self->ConstructL(aRect, aParent);
	return self;
	}
	
CTitleBar::CTitleBar()
	{
	iButtonText = NULL;
	}

CTitleBar::~CTitleBar()
	{
	delete iButtonText;
	iButtonText = NULL;
	}

void CTitleBar::ConstructL(const TRect& aRect, const CCoeControl* aParent)
	{
    if(aParent == NULL)
        {
        CreateWindowL();
        }
    else
        {
        SetContainerWindowL(*aParent);
        }
    iMargin = 20;
    SetRect(aRect);
    ActivateL();
	}

void CTitleBar::Draw(CWindowGc& gc, const TRect& aRect) const
	{
	CBaseControl::Draw(gc, aRect);
	gc.UseFont(iFont);
	TInt baseline = 0;
	baseline = aRect.Height() / 2 + iFont->AscentInPixels() / 2;
	if (iCaption)
		{
	    gc.DrawText(*iCaption, aRect, baseline, CGraphicsContext::ECenter);
		}
	if (iButtonText)
		{
		gc.DrawRoundRect(iButtonRect,TSize(2,2));
		baseline = iButtonRect.Height() / 2 + iFont->AscentInPixels() / 2;
	    gc.DrawText(*iButtonText, iButtonRect, baseline, CGraphicsContext::ELeft);
		}
	gc.DiscardFont();
	}

void CTitleBar::HandlePointerEventL(const TPointerEvent& aPointerEvent)
	{
	switch (aPointerEvent.iType)
		{
		case TPointerEvent::EButton1Down:
		case TPointerEvent::EButton2Down:
		case TPointerEvent::EButton3Down:
			{
			if (iControlEventObserver)
				iControlEventObserver->HandleControlEventL(this,EClick);
			DrawNow();
			}
			break;
		}
	}

void CTitleBar::SetLayout()
	{
	if (iButtonText)
		{
		TInt textWidth = iFont->TextWidthInPixels(*iButtonText) + 8;
		TInt textHeight = iFont->HeightInPixels() + 2;
		iButtonRect.SetRect(iMargin,Rect().iTl.iY + (Rect().Height() - textHeight)/2,iMargin + textWidth,Rect().iTl.iY + (Rect().Height() + textHeight)/2);
		}
	}

void CTitleBar::setMargin(TInt aGap)
	{
	iMargin = aGap;
	}

void CTitleBar::setButtonTextL(const TDesC& aText,TInt aActionType)
	{
	delete iButtonText;
	iButtonText = NULL;
	iButtonText = aText.AllocL();
	iActionType = aActionType;
	SetLayout();
	}

TInt CTitleBar::ActionType()
	{
	return iActionType;
	}
